import React from 'react';
import styles from './index.less';
import { Menu } from 'antd';
import type { MenuInfo } from 'rc-menu/lib/interface';
import { history } from 'umi';

// 自定义的内容
import type { MenuDataItem } from '@ant-design/pro-layout/lib/typings';
import { getShortcutMenus } from './utils';

import { useIntl } from 'umi';

type siderProps = {
  matchMenuKeys: string[];
  menuData: MenuDataItem[];
  hide?: boolean;
  iconScriptUrl?: string;
};

/**
 * 显示组件入口
 * @param props
 * @returns
 */
const SubSider: React.FC<siderProps> = (props) => {
  const { formatMessage } = useIntl();
  // menuData是全部的菜单
  const { matchMenuKeys, menuData } = props;

  // 得到一级菜单的标示
  const parentMenuKey = matchMenuKeys[0];

  // 得到这个级别下菜单的子菜单
  let subMenuData: MenuDataItem[] = [];
  for (let i = 0; i < menuData.length; i += 1) {
    const item = menuData[i];
    if (item.path === parentMenuKey) {
      subMenuData = item.children || [];
      break;
    }
  }

  // 得到快捷菜单
  let shortcutMenuData: MenuDataItem[] = [];
  if (subMenuData && subMenuData.length > 0) {
    // 如果是总览，那么要添加快捷菜单
    if (subMenuData[0].path === '/admin/welcome/home') {
      // 得到快捷菜单
      shortcutMenuData = getShortcutMenus(menuData);
    }
  }

  /**
   * 菜单点击触发事件
   * @param menu 菜单数据
   */
  const menuClicked = (menu: MenuInfo) => {
    history.push(menu.key as string);
  };

  /**
   * 返回快捷菜单的ReactNode
   * @param menu 菜单数据
   * @returns
   */
  const SubMenu = (menu: MenuDataItem) => {
    if (menu.unaccessible) {
      return '';
    }
    const text = formatMessage({
      id: menu.locale || '',
      defaultMessage: menu.name,
    });
    return (
      <Menu.Item key={menu.key || menu.path} className={styles.customerSelected}>
        {text}
      </Menu.Item>
    );
  };

  /**
   * 显示SubSider的渲染结构
   */
  return (
    <div className={styles.subsider}>
      <div className={styles.title}>Ant Mall</div>
      <div className={styles.menuBody}>
        <Menu
          mode="inline"
          selectedKeys={matchMenuKeys}
          className={styles.menu}
          onClick={menuClicked}
        >
          {subMenuData.map((menu) => {
            return SubMenu(menu);
          })}

          {/* 显示快捷菜单 */}
          {shortcutMenuData.map((menu) => {
            return SubMenu(menu);
          })}
        </Menu>
      </div>
    </div>
  );
};

export default SubSider;
